package com.million.artservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.million.artservice.client.UserClient;
import com.million.artservice.entity.ArticleComment;
import com.million.artservice.entity.params.CommentParams;
import com.million.artservice.entity.vo.CommentVo;
import com.million.artservice.entity.vo.QueryCommentPageVo;
import com.million.artservice.entity.vo.QueryCommentVo;
import com.million.artservice.mapper.ArticleCommentMapper;
import com.million.artservice.service.ArticleCommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.million.commonutils.JwtUtils;
import com.million.commonutils.orderVo.UcenterMemberVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 文章评论 服务实现类
 * </p>
 *
 * @author 十麓
 * @since 2022-04-17
 */
@Service
public class ArticleCommentServiceImpl extends ServiceImpl<ArticleCommentMapper, ArticleComment> implements ArticleCommentService {

    @Autowired
    private UserClient userClient;

    //根据文章ID显示文章评论列表
    @Override
    public List<CommentVo> queryCommentVoList (String articleId) {

        /**
         * 步骤：
         * 1、根据文章id  查询 评论列表  从comment中查询
         * 2、根据作者id  查询作者信息
         * 3、判断  如果level = 1，要去查询它有没有子评论
         * 4、如果有，根据评论id  进行查询 （parent_id）
         */
        QueryWrapper<ArticleComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", articleId);
        //判断  如果level = 1，要去查询它有没有子评论
        queryWrapper.eq("level", 1);
        List<ArticleComment> articleComments = baseMapper.selectList(queryWrapper);
        List<CommentVo> commentVoList = copyList(articleComments);
        return commentVoList;
    }

    //添加评论
    @Override
    public String addComment (CommentParams commentParams, HttpServletRequest request) {
        String byJwtToken = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(byJwtToken)) {
            return null;
        }
        ArticleComment articleComment = new ArticleComment();
        //其实是当前用户id
        articleComment.setTeacherId(byJwtToken);
        articleComment.setArticleId(commentParams.getArticleId());
        articleComment.setContent(commentParams.getContent());
        //得到父id
        String parentId = commentParams.getParentId();
        if (StringUtils.isEmpty(parentId) || parentId.equals("0")) {
            articleComment.setLevel(1);
        } else {
            articleComment.setLevel(2);
        }
        //把parent赋值给comment中得ParentId
        articleComment.setParentId(parentId == null ? "0" : parentId);
        String toUserId = commentParams.getToUserId();
        articleComment.setToUid(toUserId == null ? "0" : toUserId);
        baseMapper.insert(articleComment);
        return commentParams.getArticleId();
    }

    //分页条件查询文章评论列表  根据文章id  或者 开始时间到结束时间
    @Override
    public Page<QueryCommentPageVo> queryCommentVoPage (Page<QueryCommentPageVo> commentPageVoPage, QueryCommentVo queryCommentVo) {
        QueryWrapper<QueryCommentVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("gmtCreate");
        if (queryCommentVo == null) {
            return baseMapper.queryCommentVoPage(commentPageVoPage, queryWrapper);
        }
        String articleTitle = queryCommentVo.getArticleTitle();
        String begin = queryCommentVo.getBegin();
        String end = queryCommentVo.getEnd();
        if (!StringUtils.isEmpty(articleTitle)) {
            queryWrapper.eq("articleTitle", articleTitle);
        }
        if (!StringUtils.isEmpty(begin)) {
            queryWrapper.ge("gmtCreate", begin);
        }
        if (!StringUtils.isEmpty(end)) {
            queryWrapper.le("gmtCreate", end);
        }

        return baseMapper.queryCommentVoPage(commentPageVoPage, queryWrapper);
    }

    //根据文章评论id 删除评论信息
    @Override
    public void deleteCommentInfo (String commentId) {
        //1.如果改评论id 下面没有子评论 就直接删除
        ArticleComment articleComment = baseMapper.selectById(commentId);
        ArrayList<String> idList = new ArrayList<>(); //封装查询到的子评论id 和自身id
        idList.add(commentId);
        //如果是一级 就查询是否有子评论
        if (articleComment.getLevel().equals(1)) {
            QueryWrapper<ArticleComment> wrapper = new QueryWrapper<>();
            wrapper.eq("parent_id", commentId).select("id");
            List<ArticleComment> articleComments = baseMapper.selectList(wrapper);
            if (articleComments.size() == 0) {
                baseMapper.deleteBatchIds(idList);
                return;
            }
            articleComments.forEach(item -> {
                idList.add(item.getId());
            });
        }

        //2.如果有子评论，需要找出所有额子评论id  然后一起删除
        baseMapper.deleteBatchIds(idList);
    }

    //将ArticleComment对象 转换为Vo集合
    private List<CommentVo> copyList (List<ArticleComment> articleComments) {
        ArrayList<CommentVo> commentVos = new ArrayList<>();
        for (ArticleComment articleComment : articleComments) {
            commentVos.add(copy(articleComment));
        }
        return commentVos;
    }

    //将articleComment 对象转换为vo对象
    private CommentVo copy (ArticleComment articleComment) {
        CommentVo commentVo = new CommentVo();
        BeanUtils.copyProperties(articleComment, commentVo);
        commentVo.setId(articleComment.getId());
        commentVo.setGmtCreate(articleComment.getGmtCreate());

        //设置当前用户的信息
        //得到当前登录的用户id
        UcenterMemberVo memberInfoById = userClient.getMemberInfoById(articleComment.getTeacherId());
        commentVo.setUser(memberInfoById);

        /**
         * 子评论
         */
        Integer level = articleComment.getLevel();
        if (level == 1) {
            //获取comment的id,这个id就是子评论的父id
            String parentId = articleComment.getId();
            //通过这个id 查询子评论 返回子评论的集合
            List<CommentVo> commentVoList = findCommentsByParentId(parentId);
            commentVo.setChildrens(commentVoList);
        }

        /**
         * toUser  给谁评论
         */

        if (level > 1) {
            String toUid = articleComment.getToUid();
            //通过给谁写的id 找到给谁写的用户
            UcenterMemberVo memberInfoById1 = userClient.getMemberInfoById(toUid);
            commentVo.setToUser(memberInfoById1);
        }

        return commentVo;
    }

    //通过评论的父id 查询对应的子评论列表
    private List<CommentVo> findCommentsByParentId (String parentId) {
        QueryWrapper<ArticleComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId);
        //level等于2  就是子评论
        queryWrapper.eq("level", 2);
        List<ArticleComment> articleComments = baseMapper.selectList(queryWrapper);
        return copyList(articleComments);
    }
}
